package com.apache.portal.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 * 外部命令执行工具. 用来调用外部命令并返回结果。
 * <p>
 */

public class CmdUtils {
    private static Log log = LogFactory.getLog(CmdUtils.class);

    /**
     * 执行外部命令并获取返回值
     *
     * @param cmd
     *            外部命令
     * @return 外部命令执行的返回值
     * @throws Exception
     *             执行中的异常
     */
    public synchronized static String exeCmd(String cmd) throws Exception {
        String result = "";
        Process proc = null;
        InputStream stderr = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            log.info("开始运行命令[" + cmd + "]...");
            Runtime rt = Runtime.getRuntime();
            proc = rt.exec(cmd);
            stderr = proc.getInputStream();
            isr = new InputStreamReader(stderr, Charset.forName("GBK"));
            br = new BufferedReader(isr);
            String line = null;
            StringBuffer strbuff = new StringBuffer();
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                strbuff.append(line).append("\n");
            }
            result = strbuff.toString();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                }
            if (isr != null)
                try {
                    isr.close();
                } catch (IOException e) {
                }
            if (stderr != null)
                try {
                    stderr.close();
                } catch (IOException e) {
                }
            if (proc != null)
                proc.destroy();
        }
        return result;
    }

    /**
     * 启动命令
     *
     * @return 0为启动； 1为停止
     */
    public static Integer run_cmd(String cmd) {
        int result = 1;
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(cmd);
            result = 0;
        } catch (IOException e) {
            log.error("运行命令[" + cmd + "]出错:" + e.toString());
        } finally {
            if (null != proc) {
                proc.destroy();
            }
        }
        return result;
    }

    public static String cmd_result(String cmd) {
        Runtime rt = Runtime.getRuntime();
        String str[] = { "/bin/sh", "-c", cmd };
        Process pcs = null;
        BufferedReader br = null;
        String line = new String();
        StringBuffer buff = new StringBuffer();
        try {
            pcs = rt.exec(str);
            br = new BufferedReader(new InputStreamReader(pcs.getInputStream()));
            while ((line = br.readLine()) != null) {
                buff.append(line).append("\n");
            }
            pcs.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            System.err.println("processes was interrupted");
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
            }
            if (pcs != null) {
                // int ret = pcs.exitValue();
                pcs.destroy();
            }
        }
        return buff.toString();
    }

    public static void main(String[] args) {
        try {
            String cmd_startJar="java -jar D:\\WorkspacesGit\\plateform\\product\\apache-rpc-server\\target\\apache-rpc-server-3.0.1-SNAPSHOT.jar";
            String str1 = CmdUtils.exeCmd(cmd_startJar);
            System.out.println("执行结果--------");
            System.out.println(str1);
//            String s;
//            Process process = Runtime.getRuntime().exec("java -jar D:\\WorkspacesGit\\plateform\\product\\apache-rpc-server\\target\\apache-rpc-server-3.0.1-SNAPSHOT.jar");
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
//            while((s=bufferedReader.readLine()) != null)
//                System.out.println(s);
//            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
